<?php
class User extends ActiveRecord\Model {
    var $password = FALSE;
    static $belongs_to = array(
        array('department')
    );
    
    function before_save()
    {
        if ($this->password)
            $this->hashedpassword = User::HashPassword($this->password);
    }          
   
   function changePassword($old,$new)
   {                                                     
       
       $this->password = $new;
       $this->hashedpassword = User::HashPassword($new);
       return $this->save();
       
   }
    private static function HashPassword($password)
    {
        $salt = bin2hex(mcrypt_create_iv(32,MCRYPT_RAND));
        $hash = hash('sha256',$salt . $password);
        return $salt . $hash;
    }
    
    public  function ValidatePassword($password)
    {
        $salt = substr($this->hashedpassword,0,64);
        $hash = substr($this->hashedpassword,64,64);
        
        $password_hash = hash('sha256',$salt . $password);
        return ($password_hash == $hash);
    }
    
    public static function ValidateLogin($username , $password)
    {                                                   

            $user = User::find_by_username($username);//find_by_xxxxx => xxxx=> field name
        if ($user && $user->ValidatePassword($password))
        { 
            User::Login($user->id);
            return $user;
        }
        else
            return FALSE;
    }
    public static function Login($user_id)
    {
        $CI =& get_instance();
        $CI->session->set_userdata('user_id',$user_id);
    }
           
    public static function Logout()
    {
        $CI =& get_instance();
        $CI->session->sess_destroy();
        
    }
    
    public static function  GetUserProfile($user_id)
    {
        $user = User::find($user_id);
    }
    public static function CreateUser($userprofile)
    {

        $password = $userprofile['password'];
        $user = FALSE;
        $user = User::create($userprofile);
        return  $user;
                
    }    
    
    public function SaveProfile($data)
    {
/*        $data = array('name'=>$_POST['name'],
                      'email'=>$_POST['email'],
                      'mobilephone'=>$_POST['mobile'],
                      'lang'=>$_POST['lang'],
                      'department_id'=>$_POST['dept']);    */
                      
       $this->name = $data['name'];        
       $this->email = $data['email'];
       $this->mobilephone = $data['mobilephone'];
       $this->lang = $data['lang'];
       $this->department_id= $data['department_id'];
       return $this->save();
    }                                                                   
} // End Class Things_model





















?>
